package com.io.smartappframe.mvp.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.io.base.mvp.BaseActivity
import com.io.base.mvp.BaseAdapter
import com.io.commonlib.helper.CommonDeviceHelper
import com.io.commonlib.helper.LogHelper
import com.io.commonlib.helper.PermissionHelper
import com.io.commonlib.helper.PermissionHelper.RequestPermission
import com.io.commonlib.helper.ToastHelper
import com.io.commonlib.rxjava.ResponseErrorListenerImpl
import com.io.smartappframe.R
import com.io.smartappframe.databinding.ActivityMainBinding
import com.io.smartappframe.mvp.contract.MainContract
import com.io.smartappframe.mvp.model.entity.FunctionItem
import com.io.smartappframe.mvp.presenter.MainPresenter
import com.io.smartappframe.mvp.ui.adapter.MainAdapter
import com.tbruyelle.rxpermissions2.RxPermissions
import me.jessyan.rxerrorhandler.core.RxErrorHandler

/**
 * Description:功能列表展示页面
 * 2021-03-09 9:33
 * @author LiuMin
 */
class MainActivity : BaseActivity<MainPresenter, ActivityMainBinding>(), MainContract.IMainView,
    BaseAdapter.OnRecyclerViewItemClickListener<FunctionItem>, View.OnClickListener {

    private var list: List<FunctionItem>? = null
    private var adapter: MainAdapter? = null

    override fun initView(savedInstanceState: Bundle?): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("控件展示")
        mViewBinding.header.ivToolbarBack.visibility = View.GONE
        LogHelper.d(TAG, "DPI:${CommonDeviceHelper().getDeviceDpi(this)}")
        mPresenter = MainPresenter(this)
        initRecyclerView()
        mPresenter?.getFunctionList()
        requestPermission(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }

    override fun showSuccess(functionList: List<FunctionItem>) {
        list = functionList
        mViewBinding.recyclerView.adapter = adapter
        adapter?.setOnItemClickListener(this)
        adapter?.notifyData(list)
    }

    override fun showFail(msg: String) {
        ToastHelper.showShortToast(applicationContext, msg)
    }

    override fun onItemClick(
        view: View,
        viewBinding: ViewBinding?,
        data: FunctionItem,
        position: Int
    ) {
        mPresenter?.goOtherPage(data.id, this)
    }

    private fun initRecyclerView() {
        list = mutableListOf()
        adapter = MainAdapter()
        val layoutManager = LinearLayoutManager(this)
        mViewBinding.recyclerView.layoutManager = layoutManager
    }

    private fun requestPermission(vararg permissions: String?) {
        val rxPermissions = RxPermissions(this)
        val rxErrorHandler = RxErrorHandler.builder()
            .with(this)
            .responseErrorListener(ResponseErrorListenerImpl())
            .build()
        PermissionHelper.requestPermission(
            object : RequestPermission {
                override fun onRequestPermissionSuccess() {}
                override fun onRequestPermissionFailure(permissions: List<String>) {
                    // showDialog(context);
                }

                override fun onRequestPermissionFailureWithAskNeverAgain(permissions: List<String>) {
                    runOnUiThread { showDialog() }
                }
            },
            rxPermissions, rxErrorHandler, *permissions
        )
    }

    private var dialog: AlertDialog? = null
    private fun showDialog() {
        val dialogBuild = AlertDialog.Builder(this)
        val view: View = LayoutInflater.from(this).inflate(
            R.layout.dialog_confirm_permission,
            null, false
        )
        val cancelButton = view.findViewById<Button>(R.id.btn_cancel_dialog_confirm_delete)
        cancelButton.setText("退出")
        val confirmButton = view.findViewById<Button>(R.id.btn_confirm_dialog_confirm_delete)
        confirmButton.setText("设置")
        dialogBuild.setView(view)
        dialog = dialogBuild.create()
        dialog?.show()
        cancelButton.setOnClickListener(this)
        confirmButton.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        v?.let {
            if (v.id == R.id.btn_cancel_dialog_confirm_delete) {
                dialog?.dismiss()
                finish()
            } else if (v.id == R.id.btn_confirm_dialog_confirm_delete) {
                dialog?.dismiss()
                var intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", packageName, null)
                intent.setData(uri)
                startActivity(intent)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ToastHelper.cancelToast()
    }
}